class Solution {
    public String tree2str(TreeNode root) {
        StringBuilder ch = new StringBuilder();
        dfs(root, ch);
        return ch.toString();
    }

    private void dfs(TreeNode root, StringBuilder ch) {
        if (root == null) {
            return;
        }

        ch.append(root.val);

        if (root.left == null && root.right == null) {
            return;
        }

        ch.append('(');
        dfs(root.left, ch);
        ch.append(')');

        //左空右实，左括号不省；相反，右括号可省
        if (root.right != null) {
            ch.append('(');
            dfs(root.right, ch);
            ch.append(')');
        }
    }
}

// 定义树节点类
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class BinaryTreeString {
    public static void main(String[] args) {
        // 构建测试用树 [1,2,3,4]
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);

        Solution solution = new Solution();
        String result = solution.tree2str(root);
        System.out.println("树的字符串表示: " + result);
    }
}